package com.msc.deploy;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.io.FileUtils;


public class ProjectCopy {
	
	
	
	public static void main(String[] args) throws Exception {
		
		
		String projectPath = System.getProperty( "user.dir" );
		
		String destDirPath = projectPath + "/_update" ;
		 
		File srcDir  = new File( projectPath );
		File destDir = new File( destDirPath );
		
		if( !destDir.exists() ){
			destDir.mkdirs(); 
		}else{
			
		}
		File propfile = new File( projectPath + "/src/com/msc/deploy/projectCopy.properties");
		InputStream is = new FileInputStream( propfile ) ;
		Properties prop = new Properties();
		prop.load( is );
		is.close();
		String lastDate = prop.getProperty( "lastDate" )  ;
System.out.println("read last copied date:" + lastDate );		
		
		
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
		Date date = sdf.parse( lastDate  ); 
		 
		FileUtils.cleanDirectory( destDir );
		
		//Date date = DateUtils.parseDate( "2016-09-01 00:00:00" , "yyyy-MM-dd HH:mm:ss" );

		System.out.println("beging-----------------------");
		FileUtils.copyDirectory(srcDir, destDir,  new FileFilter() {
			@Override
			public boolean accept(File file) {
				if( file.isDirectory() ){
					return true;
				}else{
					return date.getTime() <= file.lastModified() ;
				}
			}
		});
		
		
	/*	srcDir  = new File( buildPath );
		File classDir = new File( destDirPath+"/WEB-INF" );
		FileUtils.copyDirectory(srcDir, classDir,  new FileFilter() {
			@Override
			public boolean accept(File file) {
				if( file.isDirectory() ){
					return true;
				}else{
					return date.getTime() <= file.lastModified() ;
				}
			}
		});*/
		
		deleteEmptyDirectory( destDir );
		
		System.out.println("finish-----------------------");
		
		prop.setProperty( "lastDate", sdf.format( new Date() ) );
		FileOutputStream fos = new FileOutputStream(  propfile );
		prop.store( fos , "" );
		fos.close();
	}

	static void deleteEmptyDirectory(File f) {
		if( f.isDirectory() ){
			File[] files = f.listFiles();
			for( int i = 0 ; i < files.length ; i++ ){
				deleteEmptyDirectory( files[i] );
			}
			
			if( f.listFiles().length == 0 ){
				f.delete();
			}
		}
	}

	static boolean isFolerNull(File f) {
		return f.list().length > 0;
	}
	
}
